package com.cw.jeeyt.controller.system;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.cw.jeeyt.common.ImageCode;
import com.cw.jeeyt.common.UUIDTool;
import com.cw.jeeyt.common.utils.CaptchaMaker;
import com.cw.jeeyt.common.web.BaseController;
import com.cw.jeeyt.service.bo.security.SecurityUserBo;
import com.cw.jeeyt.service.bo.security.SecurityUserVo;
import com.cw.jeeyt.core.util.SessionUtil;
import com.cw.jeeyt.api.dto.response.JsonResultDto;
import com.cw.jeeyt.service.impl.cache.ThemeCache;
import com.cw.jeeyt.service.intf.security.SecurityUserService;

/**
 * 登录注册控制层
 *
 * @author chenw
 * @version 1.0.0
 */
@Controller
@RequestMapping("/login")
public class LoginController extends BaseController {
    @Autowired
    private SecurityUserService securityUserService;
    @Autowired
    private ThemeCache themeCache;

    /**
     * 跳转到登录导航页面
     *
     * @return
     * @throws Exception
     */
    @GetMapping("/to-login")
    public ModelAndView toLogin() {
        ModelAndView mv = new ModelAndView("login");
        return mv;
    }

    /**
     * 生成图片验证码
     *
     * @throws IOException
     */
    @GetMapping("/verifyCode")
    public void generateImageCode(HttpServletResponse response, HttpSession session) throws IOException {
        // 设置响应的类型格式为图片格式
        response.setContentType("image/jpeg");
        // 禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        ImageCode vCode = new ImageCode(100, 30, 5, 10);
        session.setAttribute("verifyCode", vCode.getCode());
        vCode.write(response.getOutputStream());
    }

    /**
     * 验证输入的验证码是否正确
     *
     * @param response
     * @param imageCode
     * @throws IOException
     */
    @PostMapping("/validateCode")
    public JsonResultDto validateCode(HttpServletRequest request, HttpServletResponse response, String imageCode) {
        JsonResultDto jsonResultDto = new JsonResultDto(false);
        boolean validOk = CaptchaMaker.validate(request, response, imageCode);
        String msg = "";
        if (validOk) {
            msg = "验证码正确";
            jsonResultDto.setSuccess(true);
        } else {
            msg = "验证码错误";
        }
        jsonResultDto.setMsg(msg);
        return jsonResultDto;
    }

    @GetMapping("/changeCode/{curTime}")
    public void getCodeImage(HttpSession session, HttpServletResponse response, @PathVariable("curTime") String curTime)
    throws IOException {
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        // 图片大小
        int width = 90, height = 30;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 获取图形上下文
        Graphics g = image.getGraphics();
        // 生成随机类
        Random random = new Random();
        // 设定背景色
        g.setColor(getRandColor(200, 250));
        g.fillRect(0, 0, width, height);
        // 设定字体
        g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
        // 画边框
        // g.setColor(new Color());
        // g.drawRect(0,0,width-1,height-1);

        // 随机产生155条干扰线，使图象中的认证码不易被其它程序探测到
        g.setColor(getRandColor(160, 200));
        for (int i = 0; i < 155; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            g.drawLine(x, y, x + xl, y + yl);
        }
        // 取随机产生的认证码(4位数字)
        String sRand = "";
        for (int i = 0; i < 4; i++) {
            String rand = String.valueOf(random.nextInt(10));
            sRand += rand;
            // 将认证码显示到图象中
            g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110),
                20 + random.nextInt(110)));// 调用函数出来的颜色相同，可能是因为种子太接近，所以只能直接生成
            g.drawString(rand, 25 * i + 5, 20);
        }
        // 将认证码存入SESSION
        session.setAttribute("validateCode", sRand);
        // 图象生效
        g.dispose();
        ServletOutputStream responseOutputStream = response.getOutputStream();
        // 输出图象到页面
        ImageIO.write(image, "JPEG", responseOutputStream);
        // 以下关闭输入流！
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    /**
     * 随机颜色
     *
     * @param fc
     * @param bc
     * @return
     */
    Color getRandColor(int fc, int bc) {// 给定范围获得随机颜色
        Random random = new Random();
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

    /**
     * 跳转到登录导航页面
     *
     * @return
     */
    @GetMapping("/to-register")
    public ModelAndView toRegister() {
        ModelAndView mv = new ModelAndView("register");
        return mv;
    }

    /**
     * 跳转到找回密码页面
     *
     * @return
     */
    @GetMapping("/to-findPassword")
    public ModelAndView toFindPassword() {
        ModelAndView mv = new ModelAndView("system/system_findPassword");
        return mv;
    }

    /**
     * 验证登录是否正确
     *
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public JsonResultDto userLogin(@RequestBody SecurityUserBo userBo) {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            jsonResultDto.setSuccess(true);
            Map<String, Object> map = new HashMap<>();
            map.put("token", UUIDTool.getUUID());
            map.put("operatorId", "admin");
            map.put("operatorName", "admin");
            map.put("account", "admin");
            map.put("organId", "admin");
            map.put("organName", "admin");
            jsonResultDto.setData(map);
            //String userName = userBo.getAccount();//用户名
            //String userPwd = userBo.getPassword();//密码
            //securityUserService.checkUserLogin(userName, MD5Util.getMd5Code(userPwd));
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg(e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 验证登录是否正确
     *
     * @return
     */
    @PostMapping("/userRegister")
    public JsonResultDto userResigter(@RequestBody SecurityUserBo securityUser) throws Exception {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            securityUserService.registerUser(securityUser);
            jsonResultDto.setSuccess(true);
            jsonResultDto.setMsg("用户注册成功");
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg("用户注册失败：" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 验证登录是否正确
     *
     * @return
     */
    @PostMapping("/checkSessionUser")
    public JsonResultDto checkSessionUser() {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            SecurityUserBo securityUser = SessionUtil.getSessionUser();
            if (securityUser == null || null == securityUser.getId()) {
                jsonResultDto.setMsg("您未登录，请先登录");
            } else {
                jsonResultDto.setSuccess(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg(e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 验证登录是否正确
     *
     * @return
     */
    @PostMapping("/checkAccount")
    public JsonResultDto checkAccount(String account) {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            SecurityUserVo securityUser = securityUserService.getUserByAccount(account);
            if (securityUser != null && null != securityUser.getId()) {
                jsonResultDto.setMsg("账号已存在，请重新输入！");
                return jsonResultDto;
            }
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg(e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 跳转到登陆页面
     *
     * @return
     */
    @GetMapping("/logout")
    public ModelAndView logout(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("login");
        Authentication authentication = SecurityContextHolder.getContext()
            .getAuthentication();
        if (authentication != null) {
            new SecurityContextLogoutHandler().logout(request, response, authentication);
        }
        return mv;
    }
}
